package lemna.top.chunyu.batch.step1;


import java.util.Date;

import org.springframework.batch.core.configuration.annotation.StepScope;
import org.springframework.batch.item.file.FlatFileItemReader;
import org.springframework.batch.item.file.mapping.BeanWrapperFieldSetMapper;
import org.springframework.batch.item.file.mapping.DefaultLineMapper;
import org.springframework.batch.item.file.transform.DelimitedLineTokenizer;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Scope;
import org.springframework.core.io.FileSystemResource;
import org.springframework.core.io.Resource;

import lemna.top.chunyu.batch.config.ChunYunConfig;
import lemna.top.chunyu.batch.config.Constants;
import lemna.top.chunyu.batch.reader.CYFlatFileItemReader;
import lemna.top.chunyu.batch.step1.domain.ChunYuPaymentStatement;


@Configuration
public class Step1ReaderConfig {

	@Autowired
	ChunYunConfig config;

	@Autowired
	Resource step1File;
	
    @Bean 
    @StepScope
    public Resource step1File(@Value("#{jobParameters[date]}") Date date) {

		String dateParam = Constants.sdf1.format(date);
    	String filePath = config.getInputFilePath()+"platform-"+dateParam+".csv";
        return new FileSystemResource(filePath);
    }
    
	@Bean(name="step1Reader")
	public CYFlatFileItemReader<ChunYuPaymentStatement> step1Reader() {
		CYFlatFileItemReader<ChunYuPaymentStatement> reader = new CYFlatFileItemReader<ChunYuPaymentStatement>();
//		reader.setResource(new FileSystemResource("d:/hu/sample-data1.csv"));
//        reader.setEncoding("utf-8");
        reader.setEncoding("GBK");
//        reader.setLinesToSkip(1);

		String[] comments = { "#" };
		reader.setComments(comments);
		reader.setResource(step1File);
		reader.setLineMapper(new DefaultLineMapper<ChunYuPaymentStatement>() {
			{
				setLineTokenizer(new DelimitedLineTokenizer() {
					{
						setNames(new String[] { "chunYuOrderNo","chanelOrderNo","businessType","chanelType","createTime","completeTime","merchantNo","merchantName","terminalNo","ownMerchantNo","liquidationMerchantNo","splitMerchantNo","liquidationBankNo","clearingRate","inAccountNo","inAccountName","inAccountType","currency","orderAmount","serviceChargeRate","liquidationAmount" });
					}
				});
				setFieldSetMapper(new BeanWrapperFieldSetMapper<ChunYuPaymentStatement>() {
					{
						setTargetType(ChunYuPaymentStatement.class);
					}
				});
			}
		});
		return reader;
	}
}
